import {Component, Input, OnInit} from '@angular/core';
import {DeptStatisticalService} from './dept-statistical.service';
import {DatePipe} from '@angular/common';
import {StorageUtil} from '../../../utils/storage.util';
import {StatusEnum} from '../../../core/enum/status.enum';
import * as echarts from 'echarts';

@Component({
  selector: 'app-dept-statistical',
  templateUrl: './dept-statistical.component.html',
  styleUrls: ['./dept-statistical.component.scss'],
  providers: [DeptStatisticalService, DatePipe]
})
export class DeptStatisticalComponent implements OnInit {
  @Input() schoolParam: any = {};
  statisticsTime = [];
  searchParams: SearchParams = new SearchParams();
  userInfo: any = {};
  lineChart = null;
  pieChart = null;
  roundPieChart = null;
  polarBarChart = null;
  chartData: any = {
    deptPublishVOList: [],
    feedbackVO: {
      allCount: '',
      publishChartVO: {},
      targetChartVO: {},
      typeChartVO: {}
    },
    publishVO: {
      create: {},
      modify: {},
      stop: {}
    }
  };
  colorArr = ['#e65d63', '#67dfe2', '#359cd2', '#f59a23', '#95f204'];
  constructor(
    private http: DeptStatisticalService,
    private datePipe: DatePipe
  ) { }

  ngOnInit() {
    this.userInfo = StorageUtil.getLocalStorage('user');
    if (this.schoolParam.deptId) {
      this.searchParams.deptId = this.schoolParam.deptId;
      this.searchParams.startDate = this.schoolParam.startDate;
      this.searchParams.endDate = this.schoolParam.endDate;
    } else {
      const year = new Date().getFullYear();
      const month = new Date().getMonth() + 1 >= 10 ? new Date().getMonth() + 1 : '0' + (new Date().getMonth() + 1);
      this.searchParams.startDate = year + '-' + month + '-01';
      this.searchParams.endDate = this.datePipe.transform(new Date(), 'yyyy-MM-dd');
      this.searchParams.deptId = this.userInfo.teacher.orgId;
    }
    this.statisticsTime = [this.searchParams.startDate, this.searchParams.endDate];
    this.getInstitutionStatistics();
    this.lineChart = echarts.init(document.getElementById('lineDeptChart'));
    this.pieChart = echarts.init(document.getElementById('pieDeptChart'));
    this.roundPieChart = echarts.init(document.getElementById('roundPieDeptChart'));
    this.polarBarChart = echarts.init(document.getElementById('polarBarDeptChart'));
  }

  clickSearch() {
    this.searchParams.startDate = this.datePipe.transform(this.statisticsTime[0], 'yyyy-MM-dd');
    this.searchParams.endDate = this.datePipe.transform(this.statisticsTime[1], 'yyyy-MM-dd');
    this.getInstitutionStatistics();
  }

  getInstitutionStatistics() {
    this.http.getInstitutionStatisticsApi(this.searchParams).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.chartData.deptPublishVOList = res.datas.deptPublishVOList;
        this.chartData.publishVO = res.datas.publishVO;
        this.chartData.feedbackVO = res.datas.feedbackVO;
        this.lineChart.clear();
        this.pieChart.clear();
        this.roundPieChart.clear();
        this.polarBarChart.clear();
        this.initChart();
      }
    });
  }

  initChart() {
    const xData = [];
    const createYData = [];
    const modifyYData = [];
    const stopYData = [];
    this.chartData.publishVO.create.itemList.map(item => {
      xData.push(item.time);
      createYData.push(item.value);
    });
    this.chartData.publishVO.modify.itemList.map(item => {
      modifyYData.push(item.value);
    });
    this.chartData.publishVO.stop.itemList.map(item => {
      stopYData.push(item.value);
    });
    const lineOption = {
      title: {
        text: '每月新增、修订、停用制度数量'
      },
      tooltip: {
        trigger: 'axis'
      },
      color: this.colorArr,
      legend: {
        x: 'left',
        y: 'bottom',
        padding: [50, 0, 0, 0],
        data: ['新增制度', '修订制度', '停用制度']
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: true,
        data: xData,
        axisTick: {
          alignWithLabel: true
        }
      },
      yAxis: {
        type: 'value',
      },
      series: [
        {
          name: '新增制度',
          type: 'line',
          data: createYData
        },
        {
          name: '修订制度',
          type: 'line',
          data: modifyYData
        },
        {
          name: '停用制度',
          type: 'line',
          data: stopYData
        },
      ]
    };
    this.lineChart.setOption(lineOption);

    const legendData = Object.keys(this.chartData.feedbackVO.publishChartVO);
    const pieData = [];
    for (const o in this.chartData.feedbackVO.publishChartVO) {
      pieData.push({
        value: this.chartData.feedbackVO.publishChartVO[o],
        name: o
      });
    }

    const pieOption = {
      title: {
        text: '执行情况',
        left: 'left'
      },
      tooltip: {
        trigger: 'item'
      },
      color: this.colorArr,
      legend: {
        orient: 'vertical',
        x: 'right',
        y: 'bottom',
        data: legendData
      },
      series: [
        {
          name: '执行情况',
          type: 'pie',
          radius: '50%',
          label: {
            normal: {
              formatter: '{b}:{c}: ({d}%)'
            }
          },
          data: pieData
        }
      ]
    };
    this.pieChart.setOption(pieOption);

    const roundPieData = [];
    const roundPieLegend = Object.keys(this.chartData.feedbackVO.typeChartVO);
    for (const o in this.chartData.feedbackVO.typeChartVO) {
      roundPieData.push({
        value: this.chartData.feedbackVO.typeChartVO[o],
        name: o
      });
    }
    if (roundPieData.length === 0) {
      roundPieData.push({
        value: 0,
        name: 0
      });
    }
    const roundPieOption = {
      title: {
        text: '制度类型'
      },
      tooltip: {
        trigger: 'item'
      },
      color: this.colorArr,
      legend: {
        orient: 'vertical',
        x: 'right',
        y: 'bottom',
        data: roundPieLegend
      },
      graphic: {
        type: 'text',
        left: 'center',
        top: 'center',
        style: {
          text: '执行制度\n' + this.chartData.feedbackVO.allCount + '份',
          fill: '#000',
          fontSize: 20,
          fontWeight: '',
          textAlign: 'center'
        }
      },
      series: [
        {
          name: '制度类型',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderWidth: 2
          },
          label: {
            show: true,
            position: 'center',
            normal: {
              formatter: '{b}:{c}: ({d}%)'
            }
          },
          emphasis: {
            label: {
              show: true,
            }
          },
          labelLine: {
            show: true
          },
          data: roundPieData
        }
      ]
    };
    this.roundPieChart.setOption(roundPieOption);

    const axisData = Object.keys(this.chartData.feedbackVO.targetChartVO);
    const polarBarData = Object.values(this.chartData.feedbackVO.targetChartVO)
    const polarBarOption = {
      title: [
        {
          text: '执行作用对象'
        }
      ],
      polar: {
        radius: [30, '80%']
      },
      angleAxis: {
        startAngle: 45
      },
      radiusAxis: {
        type: 'category',
        data: axisData,
      },
      tooltip: {},
      series: {
        type: 'bar',
        data: polarBarData,
        coordinateSystem: 'polar',
        label: {
          show: true,
          position: 'middle',
          formatter: '{b}: {c}'
        }
      }
    };
    this.polarBarChart.setOption(polarBarOption);
  }

}
class SearchParams {
  deptId: string;
  startDate: any;
  endDate: any;
}
